<script>
import { mapState, mapMutations } from "vuex";
import uploadWeight from "./mixin/uploadWeight";
export default {
    mixins: [uploadWeight],
    data() {
        return {
            currentDevice: {},
            bindDeviceList: [],
            xunzhangList: [],
            isConnectIng: false,
            isNotify: false,
            balance: {},
            oldList: [],
        };
    },
    watch: {
        // 监听蓝牙设备
        "$store.state.devicesList": {
            immediate: true,
            deep: true,
            async handler(e) {
                if (e.length > 0) {
                    const myDevice = e.find((item) => item.name == "倾小体");
                    if (myDevice) {
                        const list = await this.requestDeviceList();
                        const bindDevice = list.find((item) => item.deviceId == myDevice.deviceId);
                        if (bindDevice && !this.connectDeviceId && !this.isConnectIng) {
                            this.isConnectIng = true;
                            this.connectBlue(bindDevice);
                        }
                    }
                }
            },
        },
    },
    computed: {
        ...mapState(["isLogin", "userInfo", "connectDeviceId"]),
    },
    methods: {
        ...mapMutations(["loginSaveUserInfo", "logout"]),
        mpUpdate() {
            const updateManager = uni.getUpdateManager();
            updateManager.onCheckForUpdate((res) => {
                if (res.hasUpdate == true) {
                    updateManager.onUpdateReady((res) => {
                        updateManager.applyUpdate();
                    });
                }
            });
        },
        timeToHexFunc(dec, len = 2) {
            //10进制转16进制补0
            var hex = "";
            while (dec) {
                var last = dec & 15;
                hex = String.fromCharCode((last > 9 ? 55 : 48) + last) + hex;
                dec >>= 4;
            }
            if (len) {
                while (hex.length < len) hex = "0" + hex;
            }
            return hex;
        },

        async connectBlue(item) {
            console.log("APP connectBlue", item);
            var { serviceId, characteristicId } = require("@/common/sxsBalance.js");
            console.log("connectBlue start item currentDevice", item, this.currentDevice);
            if (item.isconnect || (this.currentDevice.deviceId == item.deviceId && this.currentDevice.isconnect)) {
                this.isConnectIng = false;
                return;
            }
            try {
                await this.$store
                    .dispatch("createBLEConnection", item)
                    .then((res) => {
                        console.log("createBLEConnection then", res);
                        this.currentDevice = item;
                        this.currentDevice.isconnect = res;
                    })
                    .catch((err) => {
                        console.log("createBLEConnection catch", err);
                        if (err.errCode == -1) {
                            this.currentDevice = item;
                            this.currentDevice.isconnect = true;
                        }
                    });
                await this.$store.dispatch("checkDeviceService", {
                    deviceId: item.deviceId,
                    serviceId,
                    characteristicId,
                });
                item.serviceId = serviceId;
                item.characteristicId = characteristicId;
                if (!this.isNotify) {
                    this.notifyBLEConnectionStateChange();
                    // this.notifyBLECharacteristicValueChange(item);
                    this.isNotify = true;
                }
                this.setWifi(item);
            } catch (err) {
                console.warn("connectBlue err", err);
            }
            this.isConnectIng = false;
        },
        notifyTime(item) {
            console.log("APP 监听蓝牙连接状态的改变开始");
            let thisRandom = new Date();
            let aitTime = this.getTimeAll(thisRandom);

            let aaa = `0xF1${"0" + aitTime.year}${aitTime.month}${aitTime.ri}${aitTime.hours}${aitTime.minutes}${
                aitTime.seconds
            }`;
            console.log(aaa, aaa.length, "传递的数据，pppppp=----");

            uni.writeBLECharacteristicValue({
                deviceId: item.deviceId,
                characteristicId: item.characteristicId,
                serviceId: item.serviceId,
                value: this.convertHexStrToData(aaa),
                success: (e) => {
                    console.log("app 更改时间成功", e);
                },
                fail(err) {
                    console.log("时间同步失败", err);
                },
            });
            console.log(aitTime, "当前时间的进制问题");
        },
        getTimeAll(d) {
            let year = d.getFullYear();
            let month = d.getMonth() + 1;
            let ri = d.getDate();
            let hours = d.getHours();
            let minutes = d.getMinutes();
            let seconds = d.getSeconds();
            console.log(year + "" + month + "" + ri + "" + hours + "" + minutes + "" + seconds, "opopopooo");
            let yearOne = (year + "").slice(0, 2);
            let yearTow = (year + "").slice(2, 4);
            return {
                year: this.timeToHexFunc(year),
                // yearTow: this.timeToHexFunc(yearTow - 0),
                month: this.timeToHexFunc(month),
                ri: this.timeToHexFunc(ri),
                hours: this.timeToHexFunc(hours),
                minutes: this.timeToHexFunc(minutes),
                seconds: this.timeToHexFunc(seconds),
            };
        },
        async notifyBLEConnectionStateChange() {
            try {
                uni.onBLEConnectionStateChange((res) => {
                    console.log("APP 监听蓝牙连接状态的改变结束回调 res,currentDevice", res, this.currentDevice);
                    if (res.deviceId == this.currentDevice.deviceId) {
                        this.currentDevice.isconnect = res.connected;
                        if (res.connected == false) {
                            this.$store.commit("setConnectDeviceId", "");
                            this.$store.commit("setConnectDeviceInfo", {});
                            this.$store.commit("setDevicesList", []);
                        }
                    }
                });
            } catch (e) {
                console.warn("APP 监听蓝牙连接状态的改变 err", e);
            }
        },
        requestDeviceList() {
            return new Promise((resolve, reject) => {
                if (this.bindDeviceList.length > 0) {
                    resolve(this.bindDeviceList);
                } else {
                    if (this.userInfo.completeStatus == 1) {
                        this.request
                            .httpTokenJsonRequest("/mp-api/wx/device/list", null, "POST", true)
                            .then((res) => {
                                if (res.code == 0) {
                                    this.bindDeviceList = res.data.list;
                                    resolve(this.bindDeviceList);
                                } else {
                                    reject(false);
                                }
                            })
                            .catch((err) => {
                                reject(err);
                            });
                    } else {
                        reject(false);
                    }
                }
            });
        },
        async setWifi(deviceInfo) {
            var res = await this.$store.dispatch("getProperti", {
                deviceId: deviceInfo.deviceId,
                properti: "write",
            });
            this.balance = Object.assign(deviceInfo, res);
            console.log("getProperti", this.balance, res);
            this.notifyTime(deviceInfo);
            this.notifyValueChange();
        },
        writeBLE() {
            uni.writeBLECharacteristicValue({
                deviceId: this.balance.deviceId,
                characteristicId: this.balance.characteristicId,
                serviceId: this.balance.serviceId,
                value: this.convertHexStrToData("0xF2 0x00"),
                success: (e) => {
                    console.log("app 发送获取历史记录指令", e);
                },
                fail(err) {
                    that.errorMessage = "配网失败";
                },
            });
        },
        async notifyValueChange() {
            const res = await this.$store.dispatch("getProperti", {
                deviceId: this.balance.deviceId,
                properti: "notify",
            });
            uni.notifyBLECharacteristicValueChange({
                deviceId: this.balance.deviceId,
                serviceId: res.serviceId,
                characteristicId: res.characteristicId,
                state: true,
                type: "notification",
                complete: (res) => {
                    this.writeBLE();
                    uni.onBLECharacteristicValueChange((res) => {
                        let characteristicValue = this.ab2hex(res.value);
                        if (characteristicValue.length === 40) {
                            console.log(
                                characteristicValue,
                                "pop",
                                this.transformTime(characteristicValue.slice(22, 36)),
                            );

                            let objArr = [
                                {
                                    weight: this.transformWeight(characteristicValue.slice(0, 22)).weight,
                                    impedance: this.transformWeight(characteristicValue.slice(0, 22)).resistance,
                                    weightTime: this.transformTime(characteristicValue.slice(22, 36)),
                                },
                            ];
                            this.oldList = [...this.oldList, ...objArr];
                            if (characteristicValue.slice(36, 38) == characteristicValue.slice(38, 40)) {
                                console.log(
                                    { deviceId: this.balance.deviceId, records: this.oldList },
                                    "所有的称重记录",
                                );
                                this.request
                                    .httpTokenJsonRequest(
                                        "/mp-api/wx/deviceRecord/add",
                                        { deviceId: this.balance.deviceId, records: this.oldList },
                                        "POST",
                                        true,
                                    )
                                    .then((res) => {
                                        uni.writeBLECharacteristicValue({
                                            deviceId: this.balance.deviceId,
                                            characteristicId: this.balance.characteristicId,
                                            serviceId: this.balance.serviceId,
                                            value: this.convertHexStrToData("0xF2 0x01"),
                                            success: (e) => {
                                                console.log("指令切换成功", e);
                                            },
                                            fail(err) {
                                                that.errorMessage = "配网失败";
                                            },
                                        });
                                    });
                            }
                        } else {
                            this.getWeight(res.value);
                        }
                    });
                },
            });
        },
        convertHexStrToData(hex) {
            var typedArray = new Uint8Array(
                hex.match(/[\da-f]{2}/gi).map(function (h) {
                    return parseInt(h, 16);
                }),
            );
            return typedArray.buffer;
        },
        transformWeight(value) {
            const trimedStr = value.trim();
            const rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr;
            const len = rawStr.length;
            if (len % 2 !== 0) {
                return "Illegal Format ASCII Code!";
            }
            let weight;
            let weightArr = [];
            let resistance;
            let resistanceArr = [];
            for (let i = 0; i < len; i = i + 2) {
                if (i == 6) {
                    weightArr.push(rawStr.substr(i, 2));
                }
                if (i == 8) {
                    weightArr.push(rawStr.substr(i, 2));
                }
                if (i == 10) {
                    resistanceArr.push(rawStr.substr(i, 2));
                }
                if (i == 12) {
                    resistanceArr.push(rawStr.substr(i, 2));
                }
                if (i == 14) {
                    resistanceArr.push(rawStr.substr(i, 2));
                }
            }
            weight = (parseInt(weightArr.reverse().join(""), 16) / 100).toFixed(2);
            resistance = parseInt(resistanceArr.reverse().join(""), 16);

            return { weight, resistance };
        },
        transformTime(value) {
            const trimedStr = value.trim();
            const rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr;
            const len = rawStr.length;
            if (len % 2 !== 0) {
                return "Illegal Format ASCII Code!";
            }
            console.log(rawStr, "POOPOO时间解析");
            let timeStr = "";
            for (let i = 0; i < len; i += 2) {
                /** 年 */
                if (i === 0) {
                    timeStr += `${parseInt(rawStr.substr(i, 4), 16)}-`;
                }
                /** 月 */
                if (i === 4) {
                    timeStr += `${this.addZero(parseInt(rawStr.substr(i, 2), 16))}-`;
                }
                /** 日 */
                if (i === 6) {
                    timeStr += `${this.addZero(parseInt(rawStr.substr(i, 2), 16))} `;
                }
                /** 时 */
                if (i === 8) {
                    timeStr += `${this.addZero(parseInt(rawStr.substr(i, 2), 16))}:`;
                }
                /** 分 */
                if (i === 10) {
                    timeStr += `${this.addZero(parseInt(rawStr.substr(i, 2), 16))}:`;
                }
                /** 秒 */
                if (i === 12) {
                    timeStr += `${this.addZero(parseInt(rawStr.substr(i, 2), 16))}`;
                }
            }
            return timeStr;
        },
        addZero(num) {
            return num < 10 ? "0" + num : num;
        },
    },
    onLaunch() {
        this.mpUpdate();
        let userInfo = uni.getStorageSync("userInfo") || "";
        if (userInfo.uid) {
            this.loginSaveUserInfo(userInfo);
        }
        this.$store.dispatch("openBluetoothAdapter").then(() => {
            this.$store.dispatch("startBluetoothDevicesDiscovery");
        });
    },
    onShow: function () {
        const that = this;
        uni.getSystemInfo({
            success: function (res) {
                const width = res && res.screenWidth ? res.screenWidth : 0;
                that.$store.commit("setScreenWidth", width);
            },
        });
    },
    onHide: function () {
        console.log("App Hide");
    },
};
</script>

<style lang="scss">
/*每个页面公共css */
* {
    color: #333;
}

@import "@/uni_modules/uview-ui/index.scss";
@import "@/static/style/index.css";
@import "@/static/style/flex.css";

uni-page-body,
html {
    height: 100%;
    background-color: #f8f8f8;
    color: #333;
}

body {
    color: #333;
    font-weight: 400;
}

button::after {
    border: none;
}
</style>
